Ext.onReady(function(){
	var viewConfig = [{
			columnsText: '显示列',
			sortAscText: '升序',
			sortDescText: '降序'
		}];
	
	//调拨审核grid
	var sm = new Ext.grid.CheckboxSelectionModel({
		singleSelect : true
	});
	
	var recState = function(v){
		if(v==0)return '<span style="color:red;">未审核</span>';
		else if(v==1)return '<span style="color:green;">审核通过</span>';
		else if(v==2)return '<span style="color:red;">审核不通过</span>';
	}
	var dateConv = function(v){//日期转换
		if(!v)return;
		else{
			return new Date(v.time)
		}
	}
	
    var cmCommit = new Ext.grid.ColumnModel([sm,
		{header : '单据ID',			dataIndex : 'num',hidden:true},
		{header : '单据编号',		dataIndex : 'mov_no'},
		{header : '审核状态',		dataIndex : 'astate',renderer:recState},
		{header : '调拨部门',		dataIndex : 'uname'},
		{header : '接收部门',		dataIndex : 'backuname'}, 
		{header : '制单日期',		dataIndex : 'operdate',renderer : Ext.util.Format.dateRenderer('Y-m-d')}, 
		{header : '制单人',			dataIndex : 'pname'}, 
		{header : '审核日期',		dataIndex : 'adate',renderer : Ext.util.Format.dateRenderer('Y-m-d'),hidden:true},
		{header : '审核人',			dataIndex : 'aname',hidden:true},
		{header : '财务日期',		dataIndex : 'cw_date',renderer : Ext.util.Format.dateRenderer('Y-m-d')},
		{header : '财务标志',		dataIndex : 'cw_flag',hidden:true}
	]);
	cmCommit.defaultSortable = true;

    var storeCommit = new Ext.data.Store({
        baseParams : {
			trancode : '61110'
		},
		proxy : new Ext.data.HttpProxy({
			url : '../' + WebServiceUrl
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : 'totalProperty',
			root : 'root'
		},  
        [{name : 'num'},
		{name : 'mov_no'}, 
		{name : 'uid'}, 
		{name : 'back_uid'}, 
		{name : 'operdate',convert:dateConv},  //转换从后台传过来的DATE对象
		{name : 'pid'}, 
		{name : 'adate',convert:dateConv}, 
		{name : 'apid'}, 
		{name : 'cw_date',convert:dateConv},
		{name : 'cw_flag'},
		
		{name : 'uname'},
		{name : 'backuname'},
		{name : 'pname'},
		{name : 'aname'},
		{name : 'astate'},
		{name : 'state'}
		])
    });

    var transferCommitGrid = new Ext.grid.GridPanel({
    	id:'transferCommitGrid',
		autoScroll: true,
		store: storeCommit,
		cm: cmCommit,
		border:false,
		sm: sm,
		tbar:['条件：',{
			xtype:'textfield',
			id:'condition',
			width:100,
			selectOnFocus : true
		},'-', '审核状态：',{
				xtype : "combo",
				id : 'astate',
				store : new Ext.data.SimpleStore({
					fields : ["id", "astate"],
					data : [['','-------------'],
							['0','未审核'], 
							['1','审核通过'],
							['2','审核不通过']
						]
				}),
				displayField : 'astate',
				valueField : 'id',
				mode : 'local',
				triggerAction : 'all',
				editable : false,
				width:100,
				emptyText : '请选择状态'
			}, '-' ,{
			text:'搜索',
			iconCls : 'search',
			handler:doSearch
		},'-',{
			text:'审核',
			iconCls : 'remove',
			menu:[{
				text:"通过",
				iconCls:'accept',
				handler:function(){
					commit(1)
				}
			},"-",{
				text:"不通过",
				iconCls:'remove',
				handler:function(){
					commit(2)
				}
			}]
		}],
		bbar: new Ext.PagingToolbar({
            store: storeCommit,
            pageSize:App.pageSize,
            displayInfo: true,
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
        	emptyMsg: "没有记录"
        }),
        viewConfig:viewConfig,
		loadMask: true
    });
    
    transferCommitGrid.on('rowclick',function(Grid, rowIdx){
    	var num = Grid.getSelectionModel().getSelected().get('num');
    	var store = Ext.getCmp('gridDetail').getStore();
		store.baseParams = {
			num : num,
			trancode : '61111'
		};
		store.reload();
    	Ext.getCmp('materielGrid').show();
 		Ext.getCmp('viewport').doLayout();
    });
    storeCommit.load({params:{start:0, limit:App.pageSize}});
	
    
    
    //记录明细grid
    var cmDtail = new Ext.grid.ColumnModel([sm,
		{header : '单据编号',	dataIndex :'num',	hidden:true},
		{header : '序号',		dataIndex :'ord',	hidden:true},
		{header : '物料名称',	dataIndex :'materielName'},
		{header : '批号',		dataIndex :'batchno',hidden:true},
		{header : '厂家条码',	dataIndex :'factcode',hidden:true},
		{header : '机身码',		dataIndex :'serialNo',hidden:true},
		{header : '退回库位',	dataIndex :'pgid',hidden:true},
		{header : '生产日期',	dataIndex :'prod_date',renderer : Ext.util.Format.dateRenderer('Y-m-d'),hidden:true},
		{header : '有效期',		dataIndex :'end_date',renderer : Ext.util.Format.dateRenderer('Y-m-d'),hidden:true},
		{header : '批次',		dataIndex :'batchid',hidden:true},
		{header : '调拨数量',	dataIndex :'amount'},
		{header : '调拨价格',	dataIndex :'back_price'},
		{header : '合计',	dataIndex :'total'},
		{header : '调拨原因',	dataIndex :'cause'},
		{header : '审核意见',	dataIndex :'aret',
			editor:new Ext.form.TextField()},
		{header : '仓库审核',	dataIndex :'astate',renderer:recState},
		{header : '审核人',		dataIndex :'aname'},
		{header : '审核日期',	dataIndex :'adate',renderer : Ext.util.Format.dateRenderer('Y-m-d')},
		/*{header : '单据类型',	dataIndex :'kind',		
			renderer:function(v){
				if(v==0)return '普通单据'
				else if(v==1)return '从售后退回'
			}
		},*/
		/*{header : '门店自审',		dataIndex :'state',
			renderer:function(v){
				if(v==0)return '待审核'
				else if(v==1)return '已作废'
				else if(v==2)return '已审核'
				else if(v==3)return '处理完毕'
			}
		},*/
		{header : '接收库位',		dataIndex :'placeno_cs',hidden:true}
	]);
	cmDtail.defaultSortable = true;
	
    var storeDetail = new Ext.data.Store({
		
		proxy : new Ext.data.HttpProxy({
			url : '../' + WebServiceUrl
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : 'totalProperty',
			root : 'root'
		},  
		[{name:'num'},
		{name:'ord'},
		{name:'gid'},
		{name:'batchno'},
		{name:'factcode'},
		{name:'serialNo'},
		{name:'pgid'},
		{name:'prod_date',convert:dateConv},
		{name:'end_date',convert:dateConv},
		{name:'batchid'},
		{name:'amount'},
		{name:'back_price'},
		{name:'cause'},
		{name:'aret'},
		{name:'astate'},
		{name:'kind'},
		{name:'apid'},
		{name:'adate',convert:dateConv},
		{name:'state'},
		{name:'placeno_cs'},
		{name:'materielName'},
		{name:'aname'},
		{name:'total'}
		])
    });
    
   var gridDetail = new Ext.grid.EditorGridPanel({
    	title:'订单明细',
    	id:'gridDetail',
		autoScroll: true,
		store: storeDetail,
		cm: cmDtail,
		sm: new Ext.grid.CheckboxSelectionModel({singleSelect : true}),
		border:false,
		viewConfig:viewConfig,
		loadMask: true
    });
    

    
    
	var viewport = new Ext.Viewport({
        layout:'border',
        id:'viewport',
        split:true,
		items:[{
			split:true,
			collapsible:true,
			border:false,
			region:'center',
			layout:'fit',
			items:transferCommitGrid
		},{
			region:'south',
			layout:'fit',
			id:'materielGrid',
			border:false,
			hidden:true,
			height:150,

			items : [new Ext.TabPanel({
	    		tabPosition:'bottom',
				activeTab:0,
				enableTabScroll:true,
				items:gridDetail
			})]
		}]
	});
	
	Ext.getCmp('condition').on('specialkey', function(field, event){//注册回车事件
        if(event.getKey() == event.ENTER){
			doSearch();
        }
    })
	
    function commit(astate){
		var record = Ext.getCmp('transferCommitGrid').getSelectionModel().getSelected();
		if(!record){
			Ext.MessageBox.alert('操作错误','请先选择一条记录');
			return;
		}
		
		var store = Ext.getCmp('gridDetail').getStore();
		var json=[];
		for(i=0,cnt=store.getCount();i<cnt;i++){
			var rec = store.getAt(i);
			json.push(rec.data);
		}
				
		if(record.get('astate') == 0){
			Ext.Msg.confirm('确认操作','确定要进行审核操作?',function(btn,text){
				if(btn == 'yes'){
					
					Ext.Ajax.request( {
						url :'../'+WebServiceUrl,
						params : {
							trancode :'61116',
							detail:Ext.encode(json),
//							uname:record.get('uname'),
							astate:astate
						},
						method :'Post',
						success : function(result, request) {
							var jsonData = Ext.util.JSON.decode(result.responseText);
							if (jsonData.success) {
								Ext.MessageBox.alert('操作成功', jsonData.message);
								transferCommitGrid.getStore().reload();
								gridDetail.getStore().reload();
							} else {
								Ext.MessageBox.alert('操作失败', jsonData.message);
							}
						},
						failure : function(result, request) {
							Ext.MessageBox.alert('操作失败', '联系管理员');
						}
					});	
				}
			});
		}else{
			Ext.MessageBox.alert('提示信息','此记录已审核');
		}
	}
		
	function doSearch(){
		var condition = Ext.get('condition').getValue();//取得搜索条件
		var astate = Ext.getCmp('astate').getValue();
		
		storeCommit.baseParams = {
			condition : condition,
			astate:astate,
			trancode : '61110'
		};
		storeCommit.load({params : {start : 0,limit : App.pageSize}});
	}
})
